<template>
  <el-card class="section-card" shadow="never">
    <template #header>
      <div class="card-header">
        <span>AI 工作台</span>
        <el-space>
          <el-button size="small" @click="clear" :disabled="!history.length">清空历史</el-button>
        </el-space>
      </div>
    </template>

    <el-form :model="form" label-position="top" class="ai-form">
      <el-form-item label="提问">
        <el-input
          v-model="form.query"
          type="textarea"
          :rows="4"
          placeholder="请输入要查询的问题，如：Element Plus 表格如何定制列？"
        />
      </el-form-item>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="Top K">
            <el-slider v-model="form.topK" :min="1" :max="10" show-input />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="Temperature">
            <el-slider v-model="form.temperature" :min="0" :max="1" :step="0.1" show-input />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-checkbox v-model="form.includeMetadata">返回命中文档元数据</el-checkbox>
      </el-form-item>
      <el-button type="primary" :loading="loading" @click="send">发送</el-button>
    </el-form>

    <el-divider />

    <div v-if="history.length === 0" class="empty-panel">
      <el-empty description="暂无对话" />
    </div>
    <el-timeline v-else>
      <el-timeline-item v-for="item in history" :key="item.id" :timestamp="formatTime(item.timestamp)">
        <div class="assistant-item">
          <div class="assistant-item__question">
            <el-tag type="info">提问</el-tag>
            <p>{{ item.request.query }}</p>
          </div>
          <div class="assistant-item__answer">
            <el-tag type="success">回复</el-tag>
            <pre>{{ item.response.answer }}</pre>
            <el-collapse v-if="item.response.context?.length">
              <el-collapse-item title="命中文档上下文">
                <ul>
                  <li v-for="doc in item.response.context" :key="doc.id">
                    <strong>{{ doc.title }}</strong>
                    <br />
                    <small>{{ doc.metadata?.source }}</small>
                  </li>
                </ul>
              </el-collapse-item>
            </el-collapse>
          </div>
        </div>
      </el-timeline-item>
    </el-timeline>
  </el-card>
</template>

<script setup>
import dayjs from 'dayjs';
import { reactive, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { useConfigStore } from '@/stores/config';
import { useAiStore } from '@/stores/ai';

const aiStore = useAiStore();
const configStore = useConfigStore();
configStore.loadFromStorage();

const form = reactive({
  query: '',
  topK: configStore.topK,
  temperature: configStore.temperature,
  includeMetadata: true
});

const loading = computed(() => aiStore.loading);
const history = computed(() => aiStore.conversations);

async function send() {
  if (!form.query) {
    ElMessage.warning('请输入问题');
    return;
  }
  try {
    const response = await aiStore.runRagQuery({
      query: form.query,
      topK: form.topK,
      temperature: form.temperature,
      includeMetadata: form.includeMetadata
    });
    configStore.setTopK(form.topK);
    configStore.setTemperature(form.temperature);
    ElMessage.success('AI 查询完成');
    return response;
  } catch (error) {
    ElMessage.error(error.message || 'AI 查询失败');
  }
}

function clear() {
  aiStore.clearHistory();
}

function formatTime(value) {
  return dayjs(value).format('YYYY-MM-DD HH:mm:ss');
}
</script>

<style scoped>
.ai-form {
  max-width: 960px;
}

.assistant-item {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.assistant-item__answer pre {
  white-space: pre-wrap;
  background: #f5f7fa;
  padding: 12px;
  border-radius: 6px;
}

.empty-panel {
  padding: 24px 0;
}
</style>
